package com.apestech.api.query.sys.esb;

import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.sql.condition.FieldSqlCallback;

/**
 * @author hup
 * @create 2018-11-26-10:00
 */
public class JPARoleSql implements FieldSqlCallback {

    private String postId;
    private String type;
    private String purpose;

    public JPARoleSql(String postId, String type, String purpose){
        this.postId=postId;
        this.type=type;
        this.purpose=purpose;
    }

    @Override
    public String getFieldSql(String alias, String field, Table tab) throws Exception {
        String id=field;
        if(tab!=null && tab.getTreeId(field)!=null){
            id="TREE."+tab.getTreeId(field);
        } else if(alias!=null && !"".equals(alias)){
            id=alias+"."+id;
        }
        String sql= "( EXISTS (SELECT 1\n" +
                "  FROM AUT_POSTS ROLE1, AUT_LOCAL_PERMIT ROLE2, AUT_LOCAL_PERMIT_ITEM ROLE3\n" +
                " WHERE ROLE1.LOCAL_PERMIT_ID = ROLE2.ID\n" +
                "   AND ROLE2.ID = ROLE3.LOCAL_PERMIT_ID\n" +
                "   AND ROLE1.ID = '"+postId+"' \n" +
                "   AND ROLE3.TYPE = '"+type+"'\n" +
                "   AND ROLE3.PURPOSE = '"+purpose+"'"+
                "   AND "+id+"=ROLE3.ORG_ID ) ";
        sql=sql+" OR (SELECT NVL(COUNT(1),0) \n" +
                "  FROM AUT_POSTS ROLE1, AUT_LOCAL_PERMIT ROLE2, AUT_LOCAL_PERMIT_ITEM ROLE3\n" +
                " WHERE ROLE1.LOCAL_PERMIT_ID = ROLE2.ID\n" +
                "   AND ROLE2.ID = ROLE3.LOCAL_PERMIT_ID\n" +
                "   AND ROLE1.ID = '"+postId+"' \n" +
                "   AND ROLE3.TYPE = '"+type+"'\n" +
                "   AND ROLE3.PURPOSE = '"+purpose+"' )=0"+")";
        return sql;
    }
}
